package com.dbq.fast.common.bean;

import android.os.Bundle;
import android.text.TextUtils;

import com.dbq.fast.App;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.main.bean.ProxyDomain;
import com.dbq.fast.business.main.bean.VpnNode;
import com.dbq.fast.business.main.model.VpnModel;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.util.SpUtil;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.io.Serializable;
import java.text.SimpleDateFormat;

import static com.dbq.fast.analysis.EventConstant.EVENT_APP_ONRESUME;
import static com.dbq.fast.analysis.EventConstant.PARAM_IS_EXPIRED;
import static com.yiba.vpn.utils.Constants.IS_VISTOR;

/**
 * Created by sunkai on 2017/10/24.
 */

public class User implements Serializable {
    public static final float UNIT_DAY = 86400000f; //1天
    public static final int UNIT_30_MINUTES = 1000 * 60 * 30; //30分钟
    private boolean isLogin;
    private String token;
    private String account = "";
    private int userServiceLevel;
    private VpnNode vpnNode;
    private boolean newUser; //新设备
    private boolean newAccount; //新账户,1  ——> new user, 0 --> old user
    private String vpnId;
    private ProxyDomain proxyDomain;
    private String phone, email;//邮箱 email

    /**
     * 套餐名称
     */
    private String userServiceName;
    /**
     * 套餐剩余天数, -1：无套餐
     */
    private long userSetMealAvailableTime = -1;
    private int isVist = 0;//当前是否没有VIP套餐（或VIP套餐过期） 1是的 0 不是
    private int purchaseState = -1; //0:未消费,1:应用内付费,2:应用内订阅
    private int autoRenewing; //0:取消 1:续费
    private String parentId = ""; //上家VpnId

    public boolean isVist() {
        return isVist == 0;
    }

    public void init() {
        CustomProfile customProfile = DatabaseManager.getInstance().queryProfile();
        if (customProfile != null) {
            this.isLogin = true;
            this.token = customProfile.getToken();
            this.account = customProfile.getAccount();
            this.userServiceLevel = customProfile.getUserServiceLevel();
            this.newUser = customProfile.getNewTestService() == 1;
            this.newAccount = customProfile.getNewUserDiscount() == 1;
            this.vpnId = customProfile.getVpnId();
            this.email = customProfile.getEmail();
        }
    }

    public VpnNode loadVpnNode() {
        if (!isLogin) {
            return null;
        }
        if (vpnNode == null) {
            synchronized (this) {
                if (vpnNode == null) {
                    vpnNode = new VpnModel().getPackageInfo(User.getInstance().getToken(), User.getInstance().getAccount());
                    if (vpnNode != null) {
                        try {
                            userServiceName = vpnNode.getUserServiceName();
                            userSetMealAvailableTime = vpnNode.getUserSetMealAvailableTime();
                            isVist = vpnNode.getIsVist();
                            if (isVist == 1) {
                                SpUtil.setBoolean(IS_VISTOR, true);
                            } else {
                                SpUtil.setBoolean(IS_VISTOR, false);
                            }
                            purchaseState = vpnNode.getPurchaseState();
                            autoRenewing = vpnNode.getAutoRenewing();
//                            Log.e("yc_", "purchaseState:"+purchaseState);
//                            Log.e("yc_", "autoRenewing:"+autoRenewing);
                            reportIsExpire(vpnNode);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
        RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_VPN_NODE_LOADED);

        return vpnNode;
    }

    /**
     * 用户每天打开应用第一次上报套餐是否过期
     */
    private void reportIsExpire(VpnNode vpnNode) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateDay = sdf.format(System.currentTimeMillis());
        String recordDay = SpUtil.getString("app_onresume");

        if (!recordDay.equals(dateDay)) {
            Bundle bundle = new Bundle();
            if (vpnNode.getUserSetMealAvailableTime() > 0) {
                bundle.putString(PARAM_IS_EXPIRED, "0");
            } else {
                bundle.putString(PARAM_IS_EXPIRED, "1");
            }
            YibaAnalysis.getInstance().event(App.getContext(), EVENT_APP_ONRESUME, bundle);
            SpUtil.setString("app_onresume", dateDay);
        }
    }


    /**
     * 在缓存中加载
     */
    private void loadProxyDomain() {
        String proxyDomainStr = App.cache.getCache("proxyDomain");
        if (proxyDomainStr == null) proxyDomainStr = "{}";
        proxyDomain = GsonT.parseJson(proxyDomainStr, ProxyDomain.class);
    }

    public ProxyDomain getProxyDomain() {
        loadProxyDomain();
        return proxyDomain == null ? new ProxyDomain() : proxyDomain;
    }

    private static class SingleHolder {
        private static final User user = new User();
    }

    private User() {

    }

    public static User getInstance() {
        return SingleHolder.user;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public void setLogin(boolean login) {
        isLogin = login;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getUserServiceName() {
        return userServiceName;
    }

    public void setUserServiceName(String userServiceName) {
        this.userServiceName = userServiceName;
    }

    public String getVpnId() {
        return vpnId;
    }

    public void setVpnId(String vpnId) {
        this.vpnId = vpnId;
    }

    public int getUserSetMealAvailableTime() {
        if (userSetMealAvailableTime == -1) {
            return -1;
        }
        int remainingDay = (int) Math.ceil(userSetMealAvailableTime / UNIT_DAY);
        if (remainingDay > 0) {
            YibaAnalysis.getInstance().setUserProperty(App.getContext(), "meal_status", "normal");
        } else {
            YibaAnalysis.getInstance().setUserProperty(App.getContext(), "meal_status", "expired");
        }
        return remainingDay;
    }

    public boolean isLess30Minute() {
        return userSetMealAvailableTime <= UNIT_30_MINUTES;
    }

    public void setUserSetMealAvailableTime(long userSetMealAvailableTime) {
        this.userSetMealAvailableTime = userSetMealAvailableTime;
    }

    public int getUserServiceLevel() {
        return userServiceLevel;
    }

    public void setUserServiceLevel(int userServiceLevel) {
        this.userServiceLevel = userServiceLevel;
    }

    public VpnNode getVpnNode() {
        return vpnNode;
    }

    public void setVpnNode(VpnNode vpnNode) {
        this.vpnNode = vpnNode;
    }

    public boolean isNewUser() {
        return newUser;
    }

    public void setNewUser(boolean newUser) {
        this.newUser = newUser;
    }

    public boolean isNewAccount() {
        return newAccount;
    }

    public void setNewAccount(boolean newAccount) {
        this.newAccount = newAccount;
        //保存修改过的值
        CustomProfile customProfile = DatabaseManager.getInstance().queryProfile();
        customProfile.setNewUserDiscount(0);
        DatabaseManager.getInstance().saveProfile(customProfile);
    }

    public int getIsVist() {
        return isVist;
    }

    /**
     * @return true 拥有套餐，false ，不拥有套餐
     */
    public boolean isHaveMeal() {
        return getIsVist() == 0;
    }

    public int getPurchaseState() {
        return purchaseState;
    }

    public int getAutoRenewing() {
        return autoRenewing;
    }

    public String getParentId() {
        if (TextUtils.isEmpty(parentId)) {
            return "63027415";  //没有上家，默认用这个
        }
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public void logOut() {
        User.getInstance().setLogin(false);
        User.getInstance().setVpnNode(null);
        User.getInstance().setUserServiceName("");
        User.getInstance().setUserSetMealAvailableTime(-1);
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
